using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;
using System.Text;

namespace BlazeApps.Library.Form
{
    [Serializable()]
    public class FormDetail : Csla.BusinessBase<FormDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _formID = Guid.NewGuid();
        private string _formName = string.Empty;
        private bool _allowMultipleResponses = false;
        private Guid _currentUserID = Guid.NewGuid();
        private int _ivFormtype = 0;
        private SmartDate _expireDate = new SmartDate(false);
        private Guid _userID = Guid.NewGuid();
        private string _formCompleteMessage = String.Empty;
        private SmartDate _createDate = new SmartDate(DateTime.Today);
        private Guid _modifiedUserID = Guid.NewGuid();
        private SmartDate _modifiedDate = new SmartDate(false);
		private bool _registeredUserOnly = false;

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid FormID
        {
            get
            {
                CanReadProperty("FormID", true);
                return _formID;
            }
        }

        public string FormName
        {
            get
            {
                CanReadProperty("FormName", true);
                return _formName;
            }
            set
            {
                CanWriteProperty("FormName", true);
                if (value == null)
                    value = string.Empty;
                if (!_formName.Equals(value))
                {
                    _formName = value;
                    PropertyHasChanged("FormName");
                }
            }
        }

        public bool AllowMultipleResponses
        {
            get
            {
                CanReadProperty("AllowMultipleResponses", true);
                return _allowMultipleResponses;
            }
            set
            {
                CanWriteProperty("AllowMultipleResponses", true);
                if (!_allowMultipleResponses.Equals(value))
                {
                    _allowMultipleResponses = value;
                    PropertyHasChanged("AllowMultipleResponses");
                }
            }
        }

        public Guid CurrentUserID
        {
            get
            {
                CanReadProperty("CurrentUserID", true);
                return _currentUserID;
            }
            set
            {
                CanWriteProperty("CurrentUserID", true);
                if (!_currentUserID.Equals(value))
                {
                    _currentUserID = value;
                    PropertyHasChanged("CurrentUserID");
                }
            }
        }

        public int IvFormtype
        {
            get
            {
                CanReadProperty("IvFormtype", true);
                return _ivFormtype;
            }
            set
            {
                CanWriteProperty("IvFormtype", true);
                if (!_ivFormtype.Equals(value))
                {
                    _ivFormtype = value;
                    PropertyHasChanged("IvFormtype");
                }
            }
        }

        public DateTime ExpireDate
        {
            get
            {
                CanReadProperty("ExpireDate", true);
                return _expireDate.Date;
            }
        }

        public string ExpireDateString
        {
            get
            {
                CanReadProperty("ExpireDate", true);
                return _expireDate.Text;
            }
            set
            {
                CanWriteProperty("ExpireDate", true);
                if (value == null)
                    value = string.Empty;
                if (!_expireDate.Equals(value))
                {
                    _expireDate.Text = value;
                    PropertyHasChanged("ExpireDate");
                }
            }
        }

        public Guid UserID
        {
            get
            {
                CanReadProperty("UserID", true);
                return _userID;
            }
            set
            {
                CanWriteProperty("UserID", true);
                if (!_userID.Equals(value))
                {
                    _userID = value;
                    PropertyHasChanged("UserID");
                }
            }
        }

        public string FormCompleteMessage
        {
            get
            {
                CanReadProperty("FomrCompleteMessage", true);
                return _formCompleteMessage;
            }
            set
            {
                CanWriteProperty("FomrCompleteMessage", true);
                if (value == null)
                    value = string.Empty;
                if (!_formCompleteMessage.Equals(value))
                {
                    _formCompleteMessage = value;
                    PropertyHasChanged("FomrCompleteMessage");
                }
            }
        }

        public DateTime CreateDate
        {
            get
            {
                CanReadProperty("CreateDate", true);
                return _createDate.Date;
            }
        }

        public string CreateDateString
        {
            get
            {
                CanReadProperty("CreateDate", true);
                return _createDate.Text;
            }
            set
            {
                CanWriteProperty("CreateDate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createDate.Equals(value))
                {
                    _createDate.Text = value;
                    PropertyHasChanged("CreateDate");
                }
            }
        }

        public Guid ModifiedUserID
        {
            get
            {
                CanReadProperty("ModifiedUserID", true);
                return _modifiedUserID;
            }
        }

        public DateTime ModifiedDate
        {
            get
            {
                CanReadProperty("ModifiedDate", true);
                return _modifiedDate.Date;
            }
        }

        public string ModifiedDateString
        {
            get
            {
                CanReadProperty("ModifiedDate", true);
                return _modifiedDate.Text;
            }
            set
            {
                CanWriteProperty("ModifiedDate", true);
                if (value == null)
                    value = string.Empty;
                if (!_modifiedDate.Equals(value))
                {
                    _modifiedDate.Text = value;
                    PropertyHasChanged("ModifiedDate");
                }
            }
        }

		public bool RegisteredUserOnly
		{
			get
			{
				CanReadProperty("RegisteredUserOnly", true);
				return _registeredUserOnly;
			}
			set
			{
				CanWriteProperty("RegisteredUserOnly", true);
				if (!_registeredUserOnly.Equals(value))
				{
					_registeredUserOnly = value;
					PropertyHasChanged("RegisteredUserOnly");
				}
			}
		}

        protected override object GetIdValue()
        {
            return _formID;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // FormName
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "FormName");
            //
            // CreateDate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "CreateDateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in FormDetail
            //AuthorizationRules.AllowRead("FormID", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("FormName", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("AllowMultipleResponses", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("CurrentUserID", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("IvFormtype", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("ExpireDate", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("UserID", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("CreateDate", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("ModifiedUserID", "FormDetailReadGroup");
            //AuthorizationRules.AllowRead("ModifiedDate", "FormDetailReadGroup");

            //AuthorizationRules.AllowWrite("FormName", "FormDetailWriteGroup");
            //AuthorizationRules.AllowWrite("AllowMultipleResponses", "FormDetailWriteGroup");
            //AuthorizationRules.AllowWrite("IvFormtype", "FormDetailWriteGroup");
            //AuthorizationRules.AllowWrite("ExpireDate", "FormDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CreateDate", "FormDetailWriteGroup");
            //AuthorizationRules.AllowWrite("ModifiedDate", "FormDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in FormDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in FormDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in FormDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in FormDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("FormDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private FormDetail()
        { /* require use of factory method */
        }

        public static FormDetail NewFormDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a FormDetail");
            return DataPortal.Create<FormDetail>();
        }

        public static FormDetail GetFormDetail(Guid formID)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a FormDetail");
            return DataPortal.Fetch<FormDetail>(new Criteria(formID));
        }

        public static void DeleteFormDetail(Guid formID)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a FormDetail");
            DataPortal.Delete(new Criteria(formID));
        }

        public override FormDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a FormDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a FormDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a FormDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid FormID;

            public Criteria(Guid formID)
            {
                this.FormID = formID;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@FormID", criteria.FormID);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetFormByFormID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _formID = dr.GetGuid("FormID");
            _formName = dr.GetString("FormName");
            _allowMultipleResponses = dr.GetBoolean("AllowMultipleResponses");
            _currentUserID = dr.GetGuid("CurrentUserID");
            _ivFormtype = dr.GetInt32("IV_FormType");
            _expireDate = dr.GetSmartDate("ExpireDate", _expireDate.EmptyIsMin);
            _userID = dr.GetGuid("UserID");
            _formCompleteMessage = dr.GetString("FormCompleteMessage");
            _createDate = dr.GetSmartDate("CreateDate", _createDate.EmptyIsMin);
            _modifiedUserID = dr.GetGuid("ModifiedUserID");
            _modifiedDate = dr.GetSmartDate("ModifiedDate", _modifiedDate.EmptyIsMin);
			_registeredUserOnly = dr.GetBoolean("RegisteredUserOnly");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertForm.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@FormName", _formName);
            DAL.AddParameter("@AllowMultipleResponses", _allowMultipleResponses);
            DAL.AddParameter("@IV_FormType", _ivFormtype);
            DAL.AddParameter("@ExpireDate", _expireDate.DBValue);
            DAL.AddParameter("@CreateDate", _createDate.DBValue);
            DAL.AddParameter("@FormID", _formID);
            DAL.AddParameter("@UserID", _userID);
            DAL.AddParameter("@FormCompleteMessage", _formCompleteMessage);
			DAL.AddParameter("@RegisteredUserOnly", _registeredUserOnly);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update

        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateForm.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@FormID", _formID);
            DAL.AddParameter("@FormName", _formName);
            DAL.AddParameter("@AllowMultipleResponses", _allowMultipleResponses);
            DAL.AddParameter("@IV_FormType", _ivFormtype);
            DAL.AddParameter("@ExpireDate", _expireDate.DBValue);
            DAL.AddParameter("@FormCompleteMessage", _formCompleteMessage);
            DAL.AddParameter("@ModifiedUserID", _modifiedUserID);
            DAL.AddParameter("@ModifiedDate", _modifiedDate.DBValue);
			DAL.AddParameter("@RegisteredUserOnly", _registeredUserOnly);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_formID));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteForm.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@FormID", DbType.Guid, criteria.FormID);
        }

        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
